from django.contrib.auth import login, logout
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect

def user_login(request):
    """处理用户登录请求"""
    if request.method == 'POST':
        # 使用POST数据初始化认证表单
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            # 获取认证通过的用户对象
            user = form.get_user()
            # 登录用户，创建会话
            login(request, user)
            # 重定向到受保护页面
            return redirect('protected_page')
    else:
        # GET请求时初始化空表单
        form = AuthenticationForm()
    # 渲染登录页面并传递表单对象
    return render(request, 'login.html', {'form': form})
    # 重定向到登录页面

    # 注销当前用户

# @login_required
def protected_page(request):
    return render(request, 'protected.html')

def user_logout(request):
    logout(request)
    return redirect('login')